
import { useState, useEffect } from 'react';
import { Target, MapPin, Radar, Play, Square, Zap, Settings } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';

export default function SoundLocalization() {
  const [isTracking, setIsTracking] = useState(false);
  const [trackingMode, setTrackingMode] = useState('realtime');
  const [sensitivity, setSensitivity] = useState([75]);
  const [detectedSources, setDetectedSources] = useState<Array<{
    id: number;
    x: number;
    y: number;
    intensity: number;
    frequency: number;
    confidence: number;
  }>>([]);

  // Simulate sound source detection
  useEffect(() => {
    const interval = setInterval(() => {
      if (isTracking) {
        const newSources = Array.from({ length: Math.floor(Math.random() * 3) + 1 }, (_, i) => ({
          id: Date.now() + i,
          x: Math.random() * 300 + 50,
          y: Math.random() * 200 + 50,
          intensity: Math.random() * 100,
          frequency: Math.random() * 5000 + 100,
          confidence: Math.random() * 40 + 60,
        }));
        setDetectedSources(newSources);
      }
    }, 2000);

    return () => clearInterval(interval);
  }, [isTracking]);

  const toggleTracking = () => {
    setIsTracking(!isTracking);
    if (!isTracking) {
      setDetectedSources([]);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold text-white">音源定位</h2>
          <p className="text-gray-400">实时音源追踪与空间定位</p>
        </div>
        <div className="flex space-x-3">
          <Button
            onClick={toggleTracking}
            className={isTracking ? 'bg-red-500 hover:bg-red-600' : 'btn-primary'}
          >
            {isTracking ? (
              <>
                <Square className="w-4 h-4 mr-2" />
                停止追踪
              </>
            ) : (
              <>
                <Play className="w-4 h-4 mr-2" />
                开始追踪
              </>
            )}
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        {/* Tracking Settings */}
        <Card className="glass-card p-6">
          <h3 className="text-lg font-semibold mb-4 text-white flex items-center">
            <Settings className="w-5 h-5 mr-2" />
            追踪设置
          </h3>
          
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">追踪模式</label>
              <Select value={trackingMode} onValueChange={setTrackingMode}>
                <SelectTrigger className="input-advanced">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="realtime">实时追踪</SelectItem>
                  <SelectItem value="continuous">连续追踪</SelectItem>
                  <SelectItem value="trigger">触发追踪</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                灵敏度: {sensitivity[0]}%
              </label>
              <Slider
                value={sensitivity}
                onValueChange={setSensitivity}
                max={100}
                min={10}
                step={5}
                className="mt-2"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">定位算法</label>
              <Select defaultValue="tdoa">
                <SelectTrigger className="input-advanced">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="tdoa">TDOA算法</SelectItem>
                  <SelectItem value="beamforming">波束成形</SelectItem>
                  <SelectItem value="music">MUSIC算法</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="pt-4 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">检测范围</span>
                <span className="text-green-400">360°</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">最大距离</span>
                <span className="text-green-400">50m</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">精度</span>
                <span className="text-green-400">±0.5m</span>
              </div>
            </div>
          </div>
        </Card>

        {/* 3D Localization Map */}
        <div className="xl:col-span-2">
          <Card className="glass-card p-6">
            <h3 className="text-lg font-semibold mb-4 text-white flex items-center">
              <Radar className="w-5 h-5 mr-2" />
              空间定位图
              {isTracking && (
                <Badge className="ml-2 bg-green-500/20 text-green-400">
                  追踪中
                </Badge>
              )}
            </h3>
            
            <div className="relative h-80 bg-black/20 rounded-lg overflow-hidden">
              {/* Grid Background */}
              <div className="absolute inset-0 opacity-20">
                {Array.from({ length: 10 }, (_, i) => (
                  <div key={i} className="absolute border-gray-600" style={{
                    left: `${i * 10}%`,
                    top: 0,
                    bottom: 0,
                    borderLeft: '1px solid'
                  }} />
                ))}
                {Array.from({ length: 8 }, (_, i) => (
                  <div key={i} className="absolute border-gray-600" style={{
                    top: `${i * 12.5}%`,
                    left: 0,
                    right: 0,
                    borderTop: '1px solid'
                  }} />
                ))}
              </div>

              {/* Center Point (Microphone Array) */}
              <div className="absolute w-4 h-4 bg-blue-500 rounded-full top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-10">
                <div className="absolute inset-0 bg-blue-500 rounded-full animate-ping opacity-75"></div>
              </div>

              {/* Detected Sound Sources */}
              {detectedSources.map((source, index) => (
                <div
                  key={source.id}
                  className="absolute transform -translate-x-1/2 -translate-y-1/2 z-20"
                  style={{
                    left: `${source.x}px`,
                    top: `${source.y}px`,
                  }}
                >
                  <div className="relative">
                    <div 
                      className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white animate-pulse"
                      style={{
                        backgroundColor: `hsl(${120 - source.intensity * 1.2}, 70%, 50%)`,
                      }}
                    >
                      {index + 1}
                    </div>
                    <div className="absolute top-8 left-1/2 transform -translate-x-1/2 bg-black/80 text-white text-xs px-2 py-1 rounded whitespace-nowrap">
                      {source.frequency.toFixed(0)}Hz
                      <br />
                      {source.confidence.toFixed(1)}%
                    </div>
                    {/* Ripple Effect */}
                    <div 
                      className="absolute inset-0 rounded-full animate-ping opacity-30"
                      style={{
                        backgroundColor: `hsl(${120 - source.intensity * 1.2}, 70%, 50%)`,
                        animationDuration: `${2 - source.intensity / 100}s`,
                      }}
                    ></div>
                  </div>
                </div>
              ))}

              {/* Range Circles */}
              <div className="absolute inset-0 flex items-center justify-center">
                {[1, 2, 3].map((ring) => (
                  <div
                    key={ring}
                    className="absolute rounded-full border border-gray-600/30"
                    style={{
                      width: `${ring * 100}px`,
                      height: `${ring * 100}px`,
                    }}
                  />
                ))}
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* Detection Results */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card className="glass-card p-6">
          <h3 className="text-lg font-semibold mb-4 text-white">检测统计</h3>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-gray-400">当前音源数量</span>
              <span className="text-blue-400">{detectedSources.length}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">累计检测次数</span>
              <span className="text-blue-400">1,247</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">平均定位精度</span>
              <span className="text-green-400">94.5%</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">响应时间</span>
              <span className="text-green-400">125ms</span>
            </div>
          </div>
        </Card>

        <Card className="glass-card p-6">
          <h3 className="text-lg font-semibold mb-4 text-white">实时数据</h3>
          <div className="space-y-2">
            {detectedSources.map((source, index) => (
              <div key={source.id} className="flex items-center justify-between p-2 bg-black/20 rounded">
                <div className="flex items-center space-x-3">
                  <div className="w-2 h-2 rounded-full bg-green-400"></div>
                  <span className="text-gray-300">音源 {index + 1}</span>
                </div>
                <div className="text-right text-sm">
                  <div className="text-blue-400">{source.frequency.toFixed(0)} Hz</div>
                  <div className="text-gray-400">{source.confidence.toFixed(1)}%</div>
                </div>
              </div>
            ))}
            {detectedSources.length === 0 && !isTracking && (
              <div className="text-center text-gray-500 py-4">
                点击开始追踪以检测音源
              </div>
            )}
          </div>
        </Card>
      </div>
    </div>
  );
}
